window.uam = window.uam || {};
uam.su = uam.su || {};
uam.su.vld = uam.su.vld || {};
uam.lsnr = uam.lsnr || {};

var sessionState = "";
if (typeof(microstrategy) != 'undefined') {
	sessionState = String(microstrategy.sessionState);
}

uam.lsnr.activateUsers = function(isActivate) {
	
	var userIds = "";
	$("input[name=status]:checked").each(function(index,element) {
		if (userIds != "") {
			userIds += ","
		}
		userIds += element.value;
	});
	
	if (userIds == "") return;
	
	var params = {
				taskId : "SearchUserTask",
				TaskSubID : "ActivateUser",
				"userIds" : userIds,
				"activate" : (isActivate == true)
			}
			
	uam.utils.callTask(params, function(data) {
			
			eval("responseContent = " + data);
			if (responseContent["status"] == uam.utils.responseCode.OK) {
				// XXX display the success message
				uam.reloadPage();
			} else {
				var err = responseContent["data"] ? responseContent["data"] : "";
				// XXX display the error message
			}
		}
	);
	
}

uam.lsnr.removeUsers = function() {
	var userIds = "";
	$("input[name=status]:checked").each(function(index,element) {
		if (userIds != "") {
			userIds += ","
		}
		userIds += element.value;
	});
	
	if (userIds == "") return;
	
	alert("Are you sure to delete the selected users!");
	
	var params = {
				taskId : "SearchUserTask",
				TaskSubID : "RemoveUser",
				"userIds" : userIds
			}
			
	uam.utils.callTask(params, function(data) {
			
			eval("responseContent = " + data);
			if (responseContent["status"] == uam.utils.responseCode.OK) {
				// XXX display the success message
				uam.reloadPage();
			} else {
				var err = responseContent["data"] ? responseContent["data"] : "";
				// XXX display the error message
			}
		}
	);
		
}


uam.lsnr.openCreateSharedReportGroupDialog = function(isOpen) {
	var dialog = $(".createSharedReportGroupDialog");
	var left = $(document).scrollLeft() + ($(window).width() - dialog.width()) / 2;
	left = left > 0 ? left : 0;
	dialog.css({position:"absolute", left: left, top:"50px", "z-index":"100"});
	if (isOpen) {
		$(".message").empty();
		dialog.show();
		$("input[name='newScyGrpName']").val("").focus();
	} else {
		dialog.hide();
	}
}

uam.lsnr.createSharedReportGroup = function() {
	$(".message").empty();
	var newScyGrpName = $("input[name='newScyGrpName']").val();
	if (newScyGrpName.length == 0) {
		$(".message").append("<span class='errorBox'>Error: please enter a group name</span>");
		$("input[name='newScyGrpName']").focus();
		return;
	} 
	$(".message").append("<span class='messageBox'>Processing...</span>");
	
	var params = {
				taskId : "SearchUserTask",
				TaskSubID : "CreateSharedReportGroup",
				"newScyGrpName" : newScyGrpName,
				"session" : sessionState
			}
			
	uam.utils.callTask(params, function(data) {
			$(".message").empty();
			
			eval("responseContent = " + data);
			if (responseContent["status"] == uam.utils.responseCode.OK) {
				$(".message").append("<span class='messageBox'>The group has created.</span>");
			} else {
				var err = responseContent["data"] ? responseContent["data"] : "";
				$(".message").append("<span class='errorBox'>Error: " + responseContent["data"] + "!</span>");	
			}
		}
	);
}

uam.su.searchUser = function() {
	
	uam.su.clearSearchError();
	
	// validation
	var srhDBFld = $("input[name=searchCriteria]:checked").val();
	var query = $("#searchText").val().replace(/(^\s+)|(\s+$)/g, "");
	
	if (query.length == 0) {
		uam.su.showSearchError("Please enter search content!");//XXX translation
		return;
	}
	
	// validate the first name and last name
	if (srhDBFld=="USER_1ST_NM" || srhDBFld=="USER_LST_NM") {
		if (!new RegExp("^[a-zA-Z\_]+$").test(query)) {
			uam.su.showSearchError("Name cannot include special characters!");//XXX translation
			return;
		} else if (query.length > 40) {
			uam.su.showSearchError("The length of name cannot exceed 40 characters!");//XXX translation
			return;
		}
	} else {
		//USER_ID WORKFORCE_MBR_ID
		if (query.length > 10) {
			uam.su.showSearchError("The length of name cannot exceed 40 characters!");//XXX translation
			return;
		}
	}
	uam.search(query, srhDBFld);
	
}

uam.reloadPage = function() {
	
	var searchText = $("input[name=historyQuery]").val();
	var searchCriteria = $("input[name=historyCriteria]").val();
	
	uam.search(searchText, searchCriteria);
}

uam.search = function(searchText, searchCriteria){

	uam.utils.callTask({taskId:"SearchUserTask", TaskSubID: "searchUser", queryVal : searchText, searchDBFld:searchCriteria, session: sessionState}, function(data) {
		
		eval("responseContent = " + data);
		if (responseContent["status"] == uam.utils.responseCode.OK) {
			$("input[name=historyQuery]").val(searchText);
			$("input[name=historyCriteria]").val(searchCriteria);
			uam.su.showResultTip(responseContent.data.length, searchCriteria, searchText,responseContent["status"]);
			uam.su.showSearchResults(responseContent.data);
		}
	});
}

uam.su.showSearchError = function(msg) {
	$("#searchErrorBox").text(msg);
	$("#searchText").focus();
}
uam.su.clearSearchError = function(msg) {
	$("#searchErrorBox").empty();
}
uam.su.showResultTip = function(len, dbField, queryVal, status){
	var radioField = "";
	if(dbField=="USER_ID"){
		radioField = "Employee/Contractor Id";
	}else if(dbField=="WORKFORCE_MBR_ID"){
		radioField="ADS Id";
	}else if(dbField="USER_1ST_NM"){
		radioField="First Name";
	}else if(dbField="USER_LST_NM"){
		radioField="Last Name";
	}
	if(status!=200){
		var resultStrNo = "no results with the "+dbField+" having: " + "\""+queryVal+"\"";
		$("#showResultTip").text(resultStrNo);
	}else{
		var resultStrYes = "found "+len+" results with the "+dbField+" having: " + "\""+queryVal+"\"";
		$("#showResultTip").text(resultStrYes);
	}
}
uam.su.clearInput = function(){
	$("#searchText").val("");
}
uam.su.showSearchResults = function(jsonResults) {
	var userInfo = "userInfo";// result table id
	var searchResults = "searchResults";// result container id
	
	$("#" + userInfo).empty();
	
	// create header
	$("<tr>" +
	"<th>&nbsp;</th>" +
	"<th>Amex Web Id</th>" +
	"<th>Employee/Contractor Id</th>" +
	"<th>Full Name</th>" +
	"<th>Department</th>" +
	"<th>Business Unit</th>" +
	"<th>Cost Center</th>" +
	"<th>Phone#</th>" +
	"<th>E-Mail Address</th>" +
	"<th>Manager</th>" +
	"</tr>").appendTo("#" + userInfo);
	
	// append user information
	for (var i = 0; i < jsonResults.length; i++) {
		var obj = jsonResults[i];
		var tr = $("<tr/>").appendTo("#" + userInfo);
		
		// if user is actived
		if (obj["STATUS"] == null || obj["STATUS"] == "undefined") {
			$("<td/>").append("<input type='checkbox' onclick='return false;'>").append("<span>*</span>").appendTo(tr);
		} else {
			var color = (obj["STATUS"] == "true") ? "#00FF00" : "#FF0000";
			
			var td = $("<td/>").appendTo(tr);
			$("<input name='status' type='checkbox'>").val(obj["USER_ID"]).appendTo(td);
			$("<span>*</span>").css("color", color).appendTo(td);
		} 
		
		
		$("<td/>").append("<a href='mstrWeb?pg=vup&userId=" +obj["USER_ID"] + uam.mstrServerInfo + "' style='cusor:pointer;'>" + obj["WORKFORCE_MBR_ID"] + "</a>").appendTo(tr);
		$("<td/>").append("<a href='mstrWeb?pg=vup&userId=" + obj["USER_ID"] + uam.mstrServerInfo + "' style='cusor:pointer;'>" + obj["USER_ID"] + "</a>").appendTo(tr);
		$("<td/>").append(obj["USER_1ST_NM"]+" " + obj["USER_LST_NM"]).appendTo(tr);
		$("<td/>").append(obj["DEPT_NM"]).appendTo(tr);
		$("<td/>").append(obj["AMEX_BUS_CD"]).appendTo(tr);
		$("<td/>").append(obj["COST_CTR_CD"]).appendTo(tr);
		$("<td/>").append("602 123 4567").appendTo(tr);
		$("<td/>").append("<a href='#'>"+obj["USER_EMAIL_AD_TX"]+"</a>").appendTo(tr);
		$("<td/>").append(obj["WORKFORCE_MBR_MAN_1ST_NM"]+" "+obj["WORKFORCE_MBR_MAN_LST_NM"]).appendTo(tr);
	}
	
	$("#"+searchResults).show();
}

/*******************************************************************************
 * Validation  Block
 ******************************************************************************/
uam.su.vld.method = function () {
	jQuery.validator.addMethod("isName", function(value, element) {
		var name = /^[a-zA-Z]+$/;
		return this.optional(element) || (name.test(value));
		}, "Please remove any space, special mark, no ditigal");
	
	//remove the spave - string trim
	jQuery.validator.addMethod("regString", function(value, element) {
		return this.optional(element) || (value.indexOf("-") == -1) || (value.indexOf("(") == -1) || (value.indexOf(")") == -1);
		}, "Please remove '-', '(', ')', or space ");
	
	jQuery.validator.addMethod("noSingleQuote", function(value, element) {
		return this.optional(element) || (value.indexOf("'") == -1);
		}, "Please remove single quotes");
	
    jQuery.validator.addMethod("SelectSelected", function(value, element){
    	//alert(element);
    	return ($(element).val()!= -1);
    }, "Please select one value");
    
    jQuery.validator.addMethod("multiSelect", function(value, element){
    	return ($(element).val()!= null);
    }, "Please select one or more value");
    
    uam && uam.par && uam.par.validateSecFuncGroupRoleReason &&
    jQuery.validator.addMethod("parSecFuncGroupRole_Reason", uam.par.validateSecFuncGroupRoleReason, "Please select one or more value");
    
    jQuery.validator.addMethod("editSecFuncGroupRole_Reason", function(value, element){
    	if ($("#reasonOther").is(":checked") == true) {
    		return true;
    	} else {
    		for (var n in uam.eup.reasonList) {
    			if(uam.eup.reasonList[n] == true) {
    				return true;
    			}
    		}
    	}
    	return false;
    }, "Please select one or more value");
}

uam.su.vld.validate = function () {
	
	$("#searchUserForm").validate({
		debug:true,
		rules: {
			/*phone:{
				required: true,
				number: true,
				minlength: 10,
				maxlength: 10
			},
			costCen: {
				required: true,
				maxlength: 18
			},*/
			mgr1stName:{
				required: true,
				regString: true,
				minlength: 2,
				maxlength: 40
			},
			mgrLastName :{
				required: true,
				isName: true,
				minlength:2
			}/*,
			mgrEmail: {
				required: true,
				noSingleQuote: true,
				email: true,
				remote: "emails.action"
			},
			midName:{
				maxlength: 1,
				minlength: 0
			},
			email:{
				required: true,
				noSingleQuote: true,
				email: true,
				remote: "emails.action"
			},

			mstrProdSel:{
				"required" : true
			},

			funcGrpRole: {
				"required" : true
			},
			securityGroup: {
				"required" : true
			}*/
		},
		messages: {
			/*phone:{
				required: "Enter your phone number",
				number: "Enter your valid phone number with only digital",
				minlength: "Enter your valid phone number",
				maxlength :"Max is 10 digital numbers"
			},
			costCen:{
				required: "Enter cost center",
				maxlenght: "the max length is 18"
			},*/
			mgr1stName:{
				 required: "Enter your firstname",
				 regString: "Please remove '-', '(', ')', or space",
				 minlength: "First Name no less than two chars",
				 maxlength: "FIrst Name no more than 40 chars"
			},
		
			mgrLastName:{
				required: "Enter your last name",
				isName: "Please remove any special character and space, numeric value not allowed in name fields.",
				minlength: "Last Name no less than two chars"
			}/*,
			mgrEmail: {
				required: "Please enter an email address",
				noSingleQuote: "Please remove single qutoes",
				email: "Please enter a valid email address",
				remote: jQuery.format("{0} is already in use")
			},
			midName: {
				maxlength: "no more than two chars"
			},
			email: {
				required: "Please enter an email address",
				noSingleQuote: "Please remove single qutoes",
				email: "Please enter a valid email address",
				remote: jQuery.format("{0} is already in use")
			}*/
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function(form) {
			
			/*var options = form.mstrProdSel.options;
			for(var i = 0; i<options.length; i++){
				var opt = options[i];
				opt.selected = true;
			}*/
			
			var taskUrl = "./taskProc?taskId=N001&taskEnv=xhr&taskContentType=json&TaskSubID=VVVEditUserProfile&rand=" + (new Date()).getTime();
			
			$(form).ajaxSubmit({
				type : "post",
				url : taskUrl,
				dataType : 'json',
				success : function(data) {
					
					console.log("response data: " + data);
					
					if (data["status"] == 200) {
						//location.href = "../plugins/UAM/jsp/Exception-Access_Confirmation.jsp";
						alert("success");
					} else {
						alert("error");
					};		
				},
				error : function (XMLHttpRequest, textStatus, errorThrown) {
					console.log("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
				}
				
		    });
			return false;
		},
		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo( element.parent().next().next() );
			else if ( element.is(":checkbox") ) {
				
				if(element.attr("name") == "securityGroup") {
					error.appendTo ($("#scyGrp").next());
				} else if (element.attr("name") == "funcGrpRole") {
					error.appendTo ($("#funcGrpRoleContainer").next());
				} else {
					error.appendTo ( element.next() );
				}
				
			} else
				error.appendTo( element.parent().next() );
		},
		success: function(label) {
			label.html("&nbsp;").addClass("checked");
		},
		highlight: function(element, errorClass) {
			$(element).parent().next().find("." + errorClass).removeClass("checked");
		}
	
	});
}

$(function(){
	//uam.su.vld.validate();
});









